package vip.sweet.web.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import vip.sweet.web.filter.JwtAuthenticationFilter;
import vip.sweet.web.handler.JwtAuthenticationEntryPoint;

/**
 * @author ASUS
 * @Date 2025/7/13 17:22
 * @Descripition
 */
@Configuration
@EnableWebSecurity//开启安全配置
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)//开启权限认证,三个参数分别代表 是否启用SpringSecurityr注解，是否启用JSR250注解，是否启用PrePost注解
public class SecurityConfig {
    private static final String[] URL_WHITELIST = {
            "/sys/login", // 登录
            "/doc.html", // swagger
            "/webjars/**", // swagger
            "/swagger-resources/**", // swagger
            "/v3/**", //  swagger
            "/*/*/data/**", // 静态资源,用于调取无需认证数据
            "/static/favicon.ico", // 图标
            "/druid/**", // druid
            "/" //  首页
    };
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    /**
     * 自定义认证过滤器
     */
    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }
    /**
     * @return 身份校验机制、身份验证提供程序
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 禁用csrf(防止跨站请求伪造攻击)
                .csrf(AbstractHttpConfigurer::disable)
                .formLogin(AbstractHttpConfigurer::disable)
                // 使用无状态session，即不使用session缓存数据
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 设置白名单
                .authorizeHttpRequests(auth -> auth.requestMatchers(URL_WHITELIST).permitAll().anyRequest().authenticated())
                // 异常处理器
                .exceptionHandling(exception -> exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))
                // 添加jwt过滤器
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        http.cors(Customizer.withDefaults());//跨域支持
        return http.build();
    }
}

